﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcShoppingMall.Controllers;
using MvcShoppingMall.Model;
using MvcShoppingMall.HtmlHelper;

namespace MvcShoppingMall.Areas.Admin.Controllers
{
    public class AdminController : BaseController
    {

        #region 登录/验证码
        [HttpGet]
        public ActionResult AdminLogin()
        {

            return View();
        }

        [HttpPost]
        public ActionResult DoAdminLogin(string loginName, string loginPwd, string IsOk, string savePwd)
        {
            string StrOk = "NO";
            //将验证码转化为小写在进行比对,TempData["code"]来源于绘制验证码是保存起来的
            string isok = TempData["code"].ToString().ToLower();
            //校验验证码
            if (IsOk.Equals(isok))
            {
                //验证登录获取对象
                var LoginUser = dbContext.wst_users.Where(u => u.loginName.Equals(loginName) && u.loginPwd.Equals(loginPwd)).FirstOrDefault();
                //对象非空
                if (LoginUser != null)
                {
                    //验证管理员3商家2会员1
                    if (LoginUser.userType == 3 || LoginUser.userType == 2)
                    {
                        //保存用户登录Session/Cookies
                        Session["Admin"] = LoginUser;
                        HttpCookie cookuser = new HttpCookie("username",LoginUser.loginName);
                        Response.Cookies.Add(cookuser);

                        //验证是否勾选保存密码
                        if (savePwd.Equals("true"))
                        {
                            //保存密码
                            Session["AdminPwd"] = loginPwd;

                        }
                        else
                        {
                            //清除保存密码
                            Session.Remove("AdminPwd");
                        }
                        StrOk = "OK";//验证通过OK
                    }
                    else
                    {
                        StrOk = "TYPENO";//账户权限NO
                    }
                }
                else
                {
                    StrOk = "NO";//账户密码No
                }
            }
            else
            {
                StrOk = "ISNO";//验证码NO
            }
            return Content(StrOk);
        }
        /// <summary>
        /// 验证码保存调用
        /// </summary>
        /// <returns></returns>
        public FileResult CreateCode()
        {
            return File(CreateCodeImg(), "image/jpeg");
        }
        /// <summary>
        /// 验证码绘制
        /// </summary>
        /// <returns></returns>
        public byte[] CreateCodeImg()
        {
            //字体颜色
            Color[] color = { Color.Red, Color.Black, Color.Blue, Color.Green };
            //字体类型
            string[] font = { "黑体", "隶书", "幼圆" };
            //创建图片对象
            Bitmap image = new Bitmap(80, 24);
            //创建画板
            Graphics g = Graphics.FromImage(image);
            //使用白色清空画板
            g.Clear(Color.White);
            try
            {
                //创建随机生成器
                Random random = new Random();
                //绘制线
                for (int i = 0; i < 3; i++)
                {
                    int x1 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int x2 = random.Next(image.Width);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(color[random.Next(color.Length)]), x1, y1, x2, y2);
                }
                //绘制干扰点
                for (int i = 0; i < 20; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, color[random.Next(color.Length)]);
                }
                string validateCode = Guid.NewGuid().ToString().Replace("-", "").Substring(2, 4);

                TempData["code"] = validateCode;
                //绘制字符
                for (int i = 0; i < validateCode.Length; i++)
                {
                    g.DrawString(validateCode[i].ToString(),
                        new Font(font[random.Next(font.Length)], 15),
                        new SolidBrush(color[random.Next(color.Length)]),
                        i * 20, 5);
                }
                //绘制边框
                g.DrawRectangle(new Pen(Color.Gray), 0, 0, image.Width - 1, image.Height - 1);

                //保存图片
                MemoryStream ms = new MemoryStream();
                image.Save(ms, ImageFormat.Jpeg);
                return ms.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        #endregion

        #region 管理员修改密码

        public ActionResult revise_password()
        {

            return View();
        }
        [HttpPost]
        public ActionResult Uppassword(string loginName, string userEmail, string loginPwd, string NewloginPwd2)
        {
            //根据条件返回对象
            wst_users us = dbContext.wst_users.Where(u => u.loginName.Equals(loginName) && u.loginPwd.Equals(loginPwd)).FirstOrDefault();
            if (us != null)
            {
                us.loginPwd = NewloginPwd2;
                //讲操作保存到数据库
                int result = dbContext.SaveChanges();
                Console.WriteLine(us.loginPwd);
                //判断结果
                if (result > 0)
                {
                    wst_users users = Session["Admin"] as wst_users;
                    //判断是否是当前登录账户
                    if (users.loginName.Equals(us.loginName))
                    {
                        return Content("<script>alert('修改成功！');location.href='" + @Url.Action("AdminLogin", "Admin") + "';</script>");
                    }
                    else
                    {
                        return Content("<script>alert('修改成功！');location.href='" + @Url.Action("SAdminIndex", "Admin") + "';</script>");
                    }

                }
            }
            else
            {
                return Content("<script>alert('请确认账号密码！');location.href='" + @Url.Action("revise_password", "Admin") + "';</script>");
            }
            return View();
        }

        #endregion

        #region 商家后台首页
        public ActionResult SAdminIndex()
        {
            #region 订单统计信息

            #endregion

            //统计访问人数
            ViewBag.AppCount = HttpContext.Application["Count"];

            #region 商户统计信息
            //获取商家
            var Shop = dbContext.wst_shops.ToList();
            ViewBag.Shop = Shop;
            //计算商家总数
            int ShopCount = Shop.Count;
            ViewBag.ShopCount = ShopCount;

            //获取商品
            var Goods = dbContext.wst_goods.ToList();
            ViewBag.Goods = Goods;
            //计算商品总数
            var GoodsCount = Goods.Count;
            ViewBag.GoodsCount = GoodsCount;

            //站点交易总计
            var WebMoneyList = dbContext.orders.ToList();
            decimal MoneySum = 0;
            foreach (order item in WebMoneyList)
            {
                MoneySum += item.totalMoney;
            }
            ViewBag.MoneySum = MoneySum;
            #endregion

            #region 会员统计信息
            //会员/用户数统计
            var Users = dbContext.wst_users.ToList();
            int userCount = Users.Count;
            ViewBag.userCount = userCount;

            #endregion




            return View();
        }
        #endregion

        #region 订单列表
        public ActionResult order_list(int pageIndex = 1, int pageSize = 10)
        {
            //获取订单数据集合，以最新的添加排序
            //var orderList = dbContext.orders.Where(r => r.orderNo.Contains("") || r.userName.Contains("")).OrderByDescending(r=>r.OrderId);

            //订单总条数
            int totalCount = dbContext.orders.Count();
            //获取分页数据源
            var OrderList = dbContext.orders.OrderBy(r => r.OrderId).Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();
            //获取页面索引
            int PageIndex = string.IsNullOrEmpty(Request.QueryString["pageIndex"]) ? 1
                            : Convert.ToInt32(Request.QueryString["pageIndex"]);

            //设置总页数
            int totalPage = dbContext.orders.Count() % pageSize != 0 ? dbContext.orders.Count() / pageSize + 1
                                                                    : dbContext.orders.Count() / pageSize;

            //实例化分页类，通过数据源、当前页索引、页面大小获取该页数据
            PageList<order> pagelist = new PageList<order>(OrderList, pageIndex, pageSize, ref totalCount, ref totalPage);
            //记录是否有上一页
            ViewBag.IsUpPage = pagelist.HasPreviousPage;
            //计算上一页索引
            ViewBag.upPage = pagelist.PageIndex - 1 == 0 ? 1 : pagelist.PageIndex - 1;
            //记录是否有下一页
            ViewBag.IsNextPage = pagelist.HasNextPage;
            //计算下一页索引
            ViewBag.nextPage = pagelist.TotalPage < pagelist.PageIndex + 1 ? pagelist.TotalPage : pagelist.PageIndex + 1;

            //将数据返回页面
            return View(pagelist);
        }
        #endregion

        #region 订单详情
        public ActionResult order_detail()
        {

            return View();
        }
        #endregion

        #region 商品列表
        public ActionResult product_list()
        {
            //获取登录信息
            wst_users us = Session["Admin"] as wst_users;
            //根据登录信息查询商品集合
            var GoodsList = dbContext.wst_goods.Where(g => g.shopId == 5).ToList();
            return View();
        }
        #endregion

        #region 添加/修改/查看商品
        public ActionResult edit_product()
        {

            return View();
        }

        #endregion

        #region 商品分类
        public ActionResult product_category()
        {

            return View();
        }
        #endregion

        #region 商品回收站
        public ActionResult recycle_bin()
        {

            return View();
        }
        #endregion

        #region 会员列表
        public ActionResult user_list(int pageIndex = 1, int pageSize = 2)
        {
            //获取订单数据集合，以最新的添加排序
            //var orderList = dbContext.orders.Where(r => r.orderNo.Contains("") || r.userName.Contains("")).OrderByDescending(r=>r.OrderId);

            //会员总条数
            var userSum = dbContext.wst_users.Where(u => u.userType != 3).ToList();
            int totalCount = userSum.Count();
            //获取分页数据源
            var UserList = dbContext.wst_users.Where(u => u.userType != 3).OrderBy(u => u.userId).Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();

            ViewBag.userCount = UserList;

            //获取页面索引
            int PageIndex = string.IsNullOrEmpty(Request.QueryString["pageIndex"]) ? 1
                            : Convert.ToInt32(Request.QueryString["pageIndex"]);

            //设置总页数
            int totalPage = dbContext.wst_users.Count() % pageSize != 0 ? dbContext.wst_users.Count() / pageSize + 1
                                                                    : dbContext.wst_users.Count() / pageSize;

            //实例化分页类，通过数据源、当前页索引、页面大小获取该页数据
            PageList<wst_users> pagelist = new PageList<wst_users>(UserList, pageIndex, pageSize, ref totalCount, ref totalPage);
            //记录是否有上一页
            ViewBag.IsUpPage = pagelist.HasPreviousPage;
            //计算上一页索引
            ViewBag.upPage = pagelist.PageIndex - 1 == 0 ? 1 : pagelist.PageIndex - 1;
            //记录是否有下一页
            ViewBag.IsNextPage = pagelist.HasNextPage;
            //计算下一页索引
            ViewBag.nextPage = pagelist.TotalPage < pagelist.PageIndex + 1 ? pagelist.TotalPage : pagelist.PageIndex + 1;

            //将数据返回页面
            return View(pagelist);
        }
        #endregion

        #region 添加会员
        public ActionResult add_user()
        {

            return View();
        }
        #endregion

        #region 店铺管理员
        public ActionResult manager_list()
        {

            return View();
        }

        #endregion

        #region 站点设置
        public ActionResult basic_settings()
        {

            return View();
        }
        #endregion

        #region 站点管理员
        public ActionResult admin_list()
        {

            return View();
        }
        #endregion

        #region 广告管理
        public ActionResult advertising_list()
        {

            return View();
        }
        #endregion

        #region 会员留言管理
        public ActionResult user_message()
        {

            return View();
        }
        #endregion

        #region 商家反馈
        public ActionResult manager_message()
        {

            return View();
        }
        #endregion

        #region 上传预览Demo
        public ActionResult FileUp()
        {

            return View();
        }
        #endregion

    }
}
